<?php
namespace Home\Controller;
use Common\Lib\User;
use Home\Model\DepartmentModel;
use Home\Model\RoleModel;

class CampusRecruitmentController extends CommonController {
	protected $table="RecruitInfo";
	protected $pageSize = 13;


	public function index (){
		$D = D('RbacUser');
		 //获取所有CRM部门 (二维)
        $getalldepartments_url = "Department/getAllDepartments";
	    $alldepartments = json_decode(http_get($getalldepartments_url),true);

		$this->assign("roleList", $this->getRoles());
		$this->assign("groupList", D('Group')->where(array('status'=>1))->select());
		$this->assign("sexType", array("未定义", "男", "女"));
		$ename = $this->getRoleEname();
		/*echo 'sss';
		print_r($ename);
		echo 'kkk';*/
    	$this->assign('viewDecorator', D("Department")->decoratorView($ename));

    	//部门选项权限
    	$ename=$this->getRoleEname();

      
    	$this->assign('depart_id', $this->getDepartmentId());
    	$this->assign('departmentItem', $this->setEmployeeDepartemtnItem());
    	$this->assign('allRoles', D('Role')->getField('id,name', true));
       /* 我加的 开始*/
    	$this->assign("userNames", D("User")->getUserNames());
    	$this->assign("departmentNames", D("Department")->getDepartmentsNames());
    	$this->assign("sexType", array("未定义", "男", "女"));
    	$this->assign("sourcesType", array("2"=>"58同城", "3"=>"赶集", "4"=>"智联", "5"=>"前程", "6"=>"简历交换", "7"=>"BOSS直聘", "8"=>"内部推荐", "9"=>"其他"));
    	$this->assign('departments', D('Department')->getAllDepartments('id,name'));
    	$this->assign("sourcesList",array(array("id"=>"2","name"=>"58同城"),array("id"=>"3","name"=>"赶集"),array("id"=>"4","name"=>"智联"),array("id"=>"5","name"=>"前程"),array("id"=>"6","name"=>"简历交换"),array("id"=>"7","name"=>"BOSS直聘"),array("id"=>"8","name"=>"内部推荐"),array("id"=>"9","name"=>"其他")));
    	$this->assign("testType", array("1"=>"初试已过", "2"=>"初试未过"));
    	$this->assign("testList", array(array("id"=>"1", 'name'=>"初试已过"), array("id"=>"2", "name"=>"初试未过")));
    	$this->assign("retestType", array("1"=>"复试已过", "2"=>"复试未过"));
    	$this->assign("retestList", array(array("id"=>"1", 'name'=>"复试已过"), array("id"=>"2", "name"=>"复试未过")));
    	 $this->assign("statusList", array(array("id"=>"1", 'name'=>"入职"), array("id"=>"2", "name"=>"试用期离职")));
    	$this->assign("statusType", array("1"=>"入职", "2"=>"试用期离职"));
    	$this->assign("recommendList", array(array("id"=>"1", 'name'=>"非内部推荐"), array("id"=>"2", "name"=>"内部推荐")));
    	$this->assign('user_role_id', session('account')['userInfo']['role_id']);
    	//获取crm的部门，职能 start
    	$this->assign('allDepartmentsList',$alldepartmentsList["list"]);//一维
    	$this->assign('allDepartments',$alldepartments["list"]);//二维
    	/* 我加的 结束*/
		$this->display();
	}

	public function setQeuryCondition() {
			$department_id = I('get.department_id');
			$user_id = session('account')['userInfo']['user_id'];
			switch(session('account')['userInfo']['role_id']){
				case 18:
				if(!empty($department_id)){
					$this->M->where(array('department_id'=>$department_id,'recruit_type'=>'2'))->order("id desc");
				}else{
					$this->M->where('recruit_type = 2')->order("id desc");
				}
			    break;
			    default :
			    $this->M->where(array('department_id'=>session('account')['userInfo']['department_id'],'user_id'=>$user_id,'recruit_type'=>'2'))
			        ->order("id desc");
			}
			if (isset($_GET['name'])) {
			$this->M->where(array('name'=>array('like', I('get.name')."%")));
		    }
		    if (isset($_GET['first_test'])) {
		    		$this->M->where(array('first_test'=>$_GET['first_test']));
            }
            if (isset($_GET['retest'])) {
		    		$this->M->where(array('retest'=>$_GET['retest']));
            }
            if (isset($_GET['status'])) {
		    		$this->M->where(array('status'=>$_GET['status']));
            }
            if (isset($_GET['info_sources'])) {
		    		$this->M->where(array('info_sources'=>$_GET['info_sources']));
            }
		   

	}

	private function getDepartmentRow(){
		if (!isset($this->departmentRow)) {
			$this->departmentRow = D('Department')->find($this->getDepartmentId());
		}
		return $this->departmentRow;
	}

	private function isHrDeparment(){
		$this->getDepartmentRow();
		
		if ($this->departmentRow['type'] == DepartmentModel::HR_DEPARTMENT) {
			return true; //$_POST['department_id'] = 0;
		} else {
			return false; //$_POST['department_id'] = session('account')['userInfo']['department_id'];
		}
	}

	private function getDepartmentId(){
		// var_dump(session('account')['userInfo']['department_id']);
		if ($this->getRoleEname()=='gold') {
			return 0;
		} else {
			$depart_id = session('account')['userInfo']['department_id'];
			
			if ($depart_id == 0) {
				return 9999999;
			} else {
				return $depart_id;
			}
		}
		
	}

	

	private function setDeparmentQuery(){
		$departmentRow = $this->getDepartmentRow();
		$config = json_decode($departmentRow['config'], true);
		if (isset($config['EmployeeQueryCondition'])) {

			call_user_func(array($this, 'set'.$config['EmployeeQueryCondition']));
		}
	}



	private function setDepartmentEmployee(){
		
		$this->M->where(array(
			'user_info.department_id'=>array('eq', $this->getDepartmentId()),
			// 'role_id'=>array('NEQ', array()) 
		));

	}
	private function setAllEmployee(){
		
	}
	// 
	private function goldCondition(){
		$this->setAllEmployee();
	}

	//人事
	private function humanResourceCondition(){

		if ($this->isHrDeparment()) {
			$this->setAllEmployee();
		} else {
			$this->setDeparmentQuery();
		}
		
	}

	//人事经理
	private function hrMasterCondition(){
		$this->setAllEmployee();
	}

	//风控经理
	private function riskMasterCondition(){
		$this->setDepartmentEmployee();
	}
	//客服经理
	private function serviceMasterCondition(){
		$this->setDepartmentEmployee();
	}



	//部门经理
	private function departmentMasterCondition(){
		$this->setDepartmentEmployee();
	}


	public function setRoleCondition(){
		$this->roleEname = $this->getRoleEname();
        $funcName = $this->roleEname."Condition";
        if (method_exists($this, $funcName)) {
             call_user_func(array($this, $funcName));
        } else {
        	$this->error("没有权限EmployeeController");
        }
	}

	



	public function getRoles(){
		/*$row = M('rbac_role')->field('level')->find(session('account')['userInfo']['role_id']);
		return D('rbac_role')->where(array('level'=>array('gt', $row['level'])))->select();*/
		$departRow = D("Department")->find(session('account')['userInfo']['department_id']);
		if ($departRow) {
			return D("Department")->getEmployeeRoles($departRow['type']);
		} else {
			return D('rbac_role')->select();
		}
		
	}


	/**
	* 获取用户 角色 id
	*
	*/
	public function getUserRoles(){
		$result = D('rbac_role_user')->where(array('user_id'=> I('get.user_id',0)))->select();
		$this->ajaxReturn($result);
	}

	/**
	* 设置用户 角色 id
	*/
	public function setUserRoles(){
		$M = D('rbac_role_user');
		$user_id = I('post.user_id',0);
		$role_ids = I('post.role_ids');
		$insert_list = array();
		if (is_array($role_ids)) {
			foreach ($role_ids as $value) {
				$insert_list[] = array('role_id'=>$value, 'user_id'=>$user_id);
			}
		} else {
			$insert_list[] = array('role_id'=>$role_ids, 'user_id'=>$user_id);
		}
		
		$M->startTrans(); 
		$result = $M->where(array('user_id'=>$user_id))->delete();

		if ($result !== false) {
			$insert_result = $M->addAll($insert_list);
			if ($insert_result !== false) {
				$re = M('user_info')->data(array('user_id'=>$user_id, 'role_id'=>$role_ids))->save();
				if ($re !== false) {
					$M->commit();
					$this->success("操作成功");
				} else {
					$M->rollback();
					$this->error("操作失败".M('user_info')->getError());
				}
				
			} else {
				$M->rollback();
				$this->error("操作失败".$M->getError());
			}
		} else {
			$M->rollback();
			
			$this->error("操作失败".$M->getError());
		}
	}

	/**
	* 预处理
	*/
	public function _before_add(){
		$this->rightProcted();	
	}

	/**
	* 添加
	*/
	public function add(){
		$_POST["graduation_date"] = empty($_POST["graduation_date"])?"":UTC_to_locale_time($_POST["graduation_date"]);
		$_POST["resume_entry_date"] = empty($_POST["resume_entry_date"])?"":UTC_to_locale_time($_POST["resume_entry_date"]);
		$_POST["resume_quit_date"] = empty($_POST["resume_quit_date"])?"":UTC_to_locale_time($_POST["resume_quit_date"]);
		$_POST["interviewer_date"] = empty($_POST["interviewer_date"])?"":UTC_to_locale_time($_POST["interviewer_date"]);
		$_POST["retest_interviewer_date"] = empty($_POST["retest_interviewer_date"])?"":UTC_to_locale_time($_POST["retest_interviewer_date"]);
		$_POST['department_id'] = session('account')['userInfo']['department_id'];
		$_POST['user_id'] = session('account')['userInfo']['user_id'];
	    $_POST["recruit_type"] = 2;
	    $_POST["info_sources"] = 1;
		/*if(session('account')['userInfo']['department_id']!=0){
			$_POST['department_name'] =D("Department")->getDepartment(session('account')['userInfo']['department_id']);	
		}*/
	    if(!empty($_POST["resume_entry_date"])&&empty($_POST["resume_quit_date"])|| !empty($_POST["resume_quit_date"])&&empty($_POST["resume_entry_date"])){
			$this->error("请输入任职的开始和结束日期！");
			exit();
		}
		if($_POST["resume_entry_date"]>$_POST["resume_quit_date"]){
			$this->error("任职的开始日期不能大于结束日期！");
			exit();
		}
		/*if(!start_end_date($_POST["interviewer_date"],$_POST["retest_interviewer_date"])){
			$this->error("复试日期不能小于初试日期！");
			exit();
		}*/

		if($_POST["first_test"] == 1){
			if(!empty($_POST["retest_interviewer_date"])){
					if(!start_end_date($_POST["interviewer_date"],$_POST["retest_interviewer_date"])){
						$this->error("复试日期不能小于初试日期！");
						exit();
					}
			}else{
				$this->error("初试已过，复试日期不能为空！");
			    exit();
			}
		}
	    if(add_field_unique("recruit_info",session('account')['userInfo']['department_id'],"mphone",$_POST["mphone"])){
			$this->error("该应聘人员的信息已录入！");
			exit();
		}
		$re = $this->M->create($_POST, 1);
		if ($re) {
			$this->M->startTrans(); 
			$re['recruitInfo'] = M('recruitInfo')->create($_POST, 1);
			$id = $this->M->add($re);
			if ($id) {
					$this->M->commit();
					$this->success(L('ADD_SUCCESS'));
			} else {
				$this->M->rollback();
				$this->error($this->M->getError());
			}
		} else {
			$this->error($this->M->getError());
		}

	}



	/**
	* 编辑
	*/
		public function edit(){
		//新方法
		$_POST["graduation_date"] = $_POST["graduation_date"] == "0000-00-00"?"":UTC_to_locale_time($_POST["graduation_date"]);
		$_POST["resume_entry_date"] = $_POST["resume_entry_date"] == "0000-00-00"?"":UTC_to_locale_time($_POST["resume_entry_date"]);
		$_POST["resume_quit_date"] =$_POST["resume_quit_date"] =="0000-00-00"?"":UTC_to_locale_time($_POST["resume_quit_date"]);
		$_POST["interviewer_date"] = $_POST["interviewer_date"] == "0000-00-00"?"":UTC_to_locale_time($_POST["interviewer_date"]);
		$_POST["retest_interviewer_date"] = $_POST["retest_interviewer_date"] == "0000-00-00"?"":UTC_to_locale_time($_POST["retest_interviewer_date"]);
         $_POST["info_sources"] = 1;
   /*      if(!empty($_POST["resume_entry_date"])&&empty($_POST["resume_quit_date"])|| !empty($_POST["resume_quit_date"])&&empty($_POST["resume_entry_date"])){
			$this->error("请输入任职的开始和结束日期！");
			exit();
		}*/
		if($_POST["resume_entry_date"]>$_POST["resume_quit_date"]){
			$this->error("任职的开始日期不能大于结束日期！");
			exit();
		}
	/*	if(!start_end_date($_POST["interviewer_date"],$_POST["retest_interviewer_date"])){
			$this->error("复试日期不能小于初试日期！");
			exit();
		}*/
		if($_POST["first_test"] == 1){
			if(!empty($_POST["retest_interviewer_date"])){
					if(!start_end_date($_POST["interviewer_date"],$_POST["retest_interviewer_date"])){
						$this->error("复试日期不能小于初试日期！");
						exit();
					}
			}else{
				$this->error("初试已过，复试日期不能为空！");
			    exit();
			}
		}
        if(edit_field_unique("recruit_info",session('account')['userInfo']['department_id'],"mphone",$_POST["mphone"],$_POST["id"])){
			$this->error("该应聘人员的信息已录入！");
			exit();
		}
        $re = M('recruitInfo')->create($_POST, 2);
		if ($re) {
			if (M('recruitInfo')->where(array('id'=>I('post.id') ))->save() !== false) {
				$this->success(L('ADD_SUCCESS'));
			} else {
				$this->error($this->M->getError().$this->M->getLastSql());
			}
		} else {
			$this->error($this->M->getError().$this->M->getLastSql());
		}

	}


	public function setEmployeeEntry(){
		$id = $_POST["id"];
		$list = M("RecruitInfo")->where(array('id'=>$id ))->select();
		if($list["0"]["retest"]==1){
			if(empty($list["0"]["quit_date"])){
				$_POST["entry_date"] = UTC_to_locale_time($_POST["entry_date"]);
				$_POST["status"] = 1;
				$re = $this->M->create($_POST, 2);
				if ($re) {
					if ($this->M->save() !== false) {
						$this->success(L('ADD_SUCCESS'));
					} else {
						$this->error($this->M->getError().$this->M->getLastSql());
					}
				} else {
					$this->error($this->M->getError().$this->M->getLastSql());
				}
			}else{
				$this->error("该员工已离职，无法更改入职日期！");
			    exit();
			}
			
		}else{
			 $this->error("只有复试通过才能入职！");
		}
	}



	public function setEmployeeQuit(){
		$id = $_POST["id"];
		$list = M("RecruitInfo")->where(array('id'=>$id ))->select();
		if(!start_end_date($list["0"]["entry_date"],UTC_to_locale_time($_POST["quit_date"]))){
			$this->error("离职日期不能小于入职日期！");
			exit();
		}
		if($list["0"]["status"]==1){
			if(empty($list["0"]["quit_date"])){
				$_POST["quit_date"] = UTC_to_locale_time($_POST["quit_date"]);
				$quit_date = UTC_to_locale_time($_POST["quit_date"]);
				$entry_date = $list["0"]["entry_date"];
				$arr = explode("-",$entry_date);
				$new_month = substr($entry_date,6,1)+1;
				$retention_date  = $arr["0"]."-0".$new_month."-".$arr["2"];
				$retention_date_strtotime = strtotime($retention_date);
				if(strtotime($quit_date)<$retention_date_strtotime){
					$_POST["status"] = 2;
				}
				//$_POST["status"] = 2;
				$re = $this->M->create($_POST, 2);
				if ($re) {
					if ($this->M->save() !== false) {
						$this->success(L('ADD_SUCCESS'));
					} else {
						$this->error($this->M->getError().$this->M->getLastSql());
					}
				} else {
					$this->error($this->M->getError().$this->M->getLastSql());
				}
			}else{
				$this->error("该员工已离职，无法更改离职日期！");
			    exit();
			}
		
		}else{
			 $this->error("只有已经入职的才能离职！");
		}
	}





	public function setEmployeeDepartemtnItem(){
		if ($this->getRoleEname()=='gold') {
			return 1;
		} else if(session('account')['userInfo']['department_id']!=0){
			$row = $this->getDepartmentRow();
			if ($row['type']==DepartmentModel::HR_DEPARTMENT) {
				return 1;
			} 
		}
		return 0;
	}

	



}
